<template>
  <div class="op-log-container">
    <!-- Page Header -->
    <div class="page-header">
      <h2 class="page-title">操作日志管理</h2>
      <div class="page-description">系统用户操作记录，用于审计和问题排查</div>
    </div>

    <!-- Control Panel -->
    <div class="control-panel">
      <!-- Search Box -->
      <div class="search-box">
        <el-input
          v-model="search.reUrl"
          placeholder="搜索网址..."
          class="search-input"
          @input="onSearchChange"
          clearable
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
      </div>

      <!-- Action Buttons -->
      <div class="action-buttons">
        <el-button-group>
          <el-button type="danger" :icon="Delete" @click="deleteAll" :disabled="!hasSelection">
            删除所有选中
          </el-button>
          <el-button type="primary" :icon="RefreshRight" @click="refreshData">
            刷新数据
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- Data Summary -->
    <div class="data-summary">
      共有 <span class="highlight">{{ pagination.total }}</span> 条日志记录
    </div>

    <!-- Main Table -->
    <el-card shadow="hover" class="table-card">
      <el-table
        ref="tableRef"
        :data="tableData"
        @sort-change="sortChange"
        tooltip-effect="light"
        :show-overflow-tooltip="true"
        border
        stripe
        highlight-current-row
        style="width: 100%"
        @selection-change="handleSelectionChange"
        v-loading="loading"
        element-loading-text="加载中..."
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="用户名" width="100" sortable />
        <el-table-column
          sortable
          label="创建日期"
          width="170"
          prop="reTime"
        >
          <template #default="scope">
            <div class="date-cell">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDate(scope.row.reTime) }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="reIp"
          label="IP"
          width="130"
        >
          <template #default="scope">
            <el-tag size="small">{{ scope.row.reIp }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="reUrl" label="网址" sortable width="180">
          <template #default="scope">
            <el-tooltip :content="scope.row.reUrl" placement="top" effect="light">
              <span class="url-text">{{ scope.row.reUrl }}</span>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column prop="reMethod" label="方法" sortable width="100">
          <template #default="scope">
            <el-tag 
              size="small" 
              :type="getMethodTagType(scope.row.reMethod)"
            >
              {{ scope.row.reMethod }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="accessTime" label="响应时间" sortable width="120">
          <template #default="scope">
            <div class="response-time" :class="getResponseTimeClass(scope.row.accessTime)">
              {{ scope.row.accessTime }} ms
            </div>
          </template>
        </el-table-column>

        <el-table-column fixed="right" label="操作" width="120">
          <template #default="scope">
            <div class="action-column">
              <el-tooltip content="查看详情" placement="top">
                <el-button
                  link
                  type="primary"
                  :icon="View"
                  circle
                  size="small"
                  @click="viewDetails(scope.row)"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top">
                <el-button
                  link
                  type="danger"
                  :icon="Delete"
                  circle
                  size="small"
                  @click="deleteRow(scope)"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- Pagination -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
      />
    </div>

    <!-- Details Dialog -->
    <el-dialog 
      v-model="detailsVisible" 
      title="操作日志详情" 
      width="60%" 
      destroy-on-close
      center
    >
      <div v-if="selectedRecord" class="record-details">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="用户名">{{ selectedRecord.username }}</el-descriptions-item>
          <el-descriptions-item label="操作时间">{{ formatDate(selectedRecord.reTime) }}</el-descriptions-item>
          <el-descriptions-item label="IP地址">{{ selectedRecord.reIp }}</el-descriptions-item>
          <el-descriptions-item label="访问网址">{{ selectedRecord.reUrl }}</el-descriptions-item>
          <el-descriptions-item label="请求方法">{{ selectedRecord.reMethod }}</el-descriptions-item>
          <el-descriptions-item label="响应时间">{{ selectedRecord.accessTime }} ms</el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailsVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  opLogPage,
  opLogDeleteByUserId,
  opLogDeleteBatch,
  opLogAdd,
  opLogEdit,
} from "@/apis/admin/opLog";
import { Delete, Edit, Plus, Search, RefreshRight, View, Calendar } from "@element-plus/icons-vue";
import { reactive, onMounted, ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";

// 表格数据
const tableData = ref([]);
const loading = ref(false);
const hasSelection = ref(false);
const detailsVisible = ref(false);
const selectedRecord = ref(null);

// 搜索条件
const search = reactive({
  reUrl: "",
});

// 排序字段
const orders = reactive({
  column: "id",
  isAsc: true,
});

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});

// 表格引用
const tableRef = ref();

// 处理选择变化
const handleSelectionChange = (selection) => {
  hasSelection.value = selection.length > 0;
};

// 搜索处理
const onSearchChange = () => {
  pagination.page = 1; // 重置到第一页
  getPage();
};

// 刷新数据
const refreshData = () => {
  getPage();
  ElMessage({
    message: '数据已刷新',
    type: 'success',
    duration: 2000
  });
};

// 表格排序函数
const sortChange = ({ prop, order }) => {
  Object.assign(orders, {
    column: prop,
    isAsc: order === "ascending",
  });
  getPage();
};

// 查看详情
const viewDetails = (row) => {
  selectedRecord.value = row;
  detailsVisible.value = true;
};

// 删除一行
const deleteRow = (scope) => {
  ElMessageBox.confirm(
    '确定要删除这条日志记录吗？此操作不可恢复。',
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    loading.value = true;
    opLogDeleteByUserId(scope.row.id).then((result) => {
      ElMessage({
        type: 'success',
        message: '删除成功'
      });
      getPage();
    }).finally(() => {
      loading.value = false;
    });
  }).catch(() => {
    // 取消删除
  });
};

// 删除所有选中行
const deleteAll = () => {
  const selectionRows = tableRef.value.getSelectionRows();
  if (selectionRows.length === 0) {
    ElMessage({
      message: '请至少选择一条记录',
      type: 'warning'
    });
    return;
  }

  ElMessageBox.confirm(
    `确定要删除选中的 ${selectionRows.length} 条记录吗？此操作不可恢复。`,
    '确认批量删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    loading.value = true;
    const ids = selectionRows.map(row => row.id);
    try {
      await opLogDeleteBatch(ids);
      ElMessage({
        type: 'success',
        message: '批量删除成功'
      });
      getPage();
    } catch (error) {
      ElMessage({
        type: 'error',
        message: '删除失败，请重试'
      });
    } finally {
      loading.value = false;
    }
  }).catch(() => {
    // 取消删除
  });
};

// 分页改变处理
const handleSizeChange = (val) => {
  pagination.size = val;
  getPage();
};

const handleCurrentChange = (val) => {
  pagination.page = val;
  getPage();
};

// 获取分页数据
const getPage = async () => {
  loading.value = true;
  try {
    const result = await opLogPage(
      {
        search: search,
        orders: [orders],
      },
      pagination.page,
      pagination.size
    );

    if (result !== undefined) {
      tableData.value = result.data.records;
      pagination.total = result.data.total;
    }
  } catch (error) {
    ElMessage({
      type: 'error',
      message: '获取数据失败，请刷新重试'
    });
  } finally {
    loading.value = false;
  }
};

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

// 获取方法标签类型
const getMethodTagType = (method) => {
  const methods = {
    'GET': 'primary',
    'POST': 'success',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  };
  return methods[method] || '';
};

// 响应时间样式
const getResponseTimeClass = (time) => {
  if (time < 100) return 'fast';
  if (time < 500) return 'medium';
  return 'slow';
};

// 生命周期
onMounted(() => {
  getPage();
});
</script>

<style scoped lang="less">
.op-log-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: 100vh;
}

.page-header {
  margin-bottom: 24px;
  
  .page-title {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    margin: 0 0 8px 0;
  }
  
  .page-description {
    font-size: 14px;
    color: #606266;
  }
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  
  .search-box {
    width: 300px;
    
    .search-input {
      width: 100%;
    }
  }
}

.data-summary {
  font-size: 14px;
  color: #606266;
  margin-bottom: 16px;
  
  .highlight {
    color: #409EFF;
    font-weight: bold;
  }
}

.table-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.date-cell {
  display: flex;
  align-items: center;
  gap: 5px;
}

.url-text {
  display: inline-block;
  max-width: 160px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.action-column {
  display: flex;
  justify-content: center;
  gap: 8px;
}

.response-time {
  font-weight: 600;
  
  &.fast {
    color: #67C23A;
  }
  
  &.medium {
    color: #E6A23C;
  }
  
  &.slow {
    color: #F56C6C;
  }
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.record-details {
  padding: 10px;
}

.dialog-footer {
  text-align: right;
}
</style>